package io.renren.modules.substation.controller;

import java.io.InputStream;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import io.renren.common.exception.RRException;
import io.renren.common.utils.CsvtojsonUtils;
import io.renren.modules.substation.entity.TInfoAreaInfoEntity;
import io.renren.modules.substation.entity.TInfoEfenceInfoPEntity;
import io.renren.modules.substation.entity.TInfoEfenceInfoPShow;
import io.renren.modules.substation.service.TInfoAreaInfoService;
import io.renren.modules.sys.entity.SysLogEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.substation.entity.TInfoEfenceAreaEntity;
import io.renren.modules.substation.service.TInfoEfenceAreaService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartFile;


/**
 * 围栏区域图
 *
 * @author yzx
 * @email sunlightcs@gmail.com
 * @date 2020-07-18 12:47:29
 */
@RestController
@RequestMapping("substation/tinfoefencearea")
public class TInfoEfenceAreaController {
    private static Logger logger = LoggerFactory.getLogger(TInfoEfenceAreaController.class);
    private static  Map<String, Object> fileFormat = null;
    @Autowired
    private TInfoEfenceAreaService tInfoEfenceAreaService;
    @Autowired
    private TInfoAreaInfoService tInfoAreaInfoService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("substation:tinfoefencearea:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = tInfoEfenceAreaService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{tableId}")
    @RequiresPermissions("substation:tinfoefencearea:info")
    public R info(@PathVariable("tableId") Long tableId){
		TInfoEfenceAreaEntity tInfoEfenceArea = tInfoEfenceAreaService.getById(tableId);

        return R.ok().put("tInfoEfenceArea", tInfoEfenceArea);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("substation:tinfoefencearea:save")
    public R save(@RequestBody TInfoEfenceAreaEntity tInfoEfenceArea){
		tInfoEfenceAreaService.save(tInfoEfenceArea);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("substation:tinfoefencearea:update")
    public R update(@RequestBody TInfoEfenceAreaEntity tInfoEfenceArea){
		tInfoEfenceAreaService.updateById(tInfoEfenceArea);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("substation:tinfoefencearea:delete")
    public R delete(@RequestBody Long[] tableIds){
		tInfoEfenceAreaService.removeByIds(Arrays.asList(tableIds));

        return R.ok();
    }

    /**
     * 列表
     */
    @RequestMapping("/listarea/{devArea}")
//    @RequiresPermissions("substation:tinfoefencearea:listarea")
    public R listarea(@PathVariable("devArea") long devArea){
//        PageUtils page = tInfoEfenceAreaService.queryPage(params);
//        List<TInfoEfenceAreaEntity> list = null;
        TInfoEfenceAreaEntity tInfoEfenceAreaEntity = new TInfoEfenceAreaEntity();
        tInfoEfenceAreaEntity.setDevArea(devArea);
        List<TInfoEfenceAreaEntity> list = tInfoEfenceAreaService.getValueByDevArea(tInfoEfenceAreaEntity);
//        list.add(tInfoEfenceAreaEntity);
        return R.ok().put("list", list);
    }

    /**
     * 列表
     */
    @RequestMapping("/listallarea")
//    @RequiresPermissions("substation:tinfoefencearea:listarea")
    public R listallarea(){
//        PageUtils page = tInfoEfenceAreaService.queryPage(params);
        List<TInfoAreaInfoEntity> listarea = tInfoAreaInfoService.list();
        List<TInfoEfenceAreaEntity> list = tInfoEfenceAreaService.list();
        for(int i=0;i<list.size();i++){
            for(int j=0;j<listarea.size();j++){
                if(list.get(i).getDevArea() == listarea.get(j).getAreaId()){
                    list.get(i).setAreaName(listarea.get(j).getAreaName());
                }
            }
        }
        return R.ok().put("list", list);
    }

    /**
     * 列表区域所有围栏点
     */
    @RequestMapping("/listareaalldev/{devArea}")
//    @RequiresPermissions("substation:tinfoefencearea:listareaalldev")
    public R listarea(@PathVariable("devArea") Long devArea){
//        PageUtils page = tInfoEfenceAreaService.queryPage(params);
//        List<TInfoEfenceAreaEntity> list = null;
        List<TInfoEfenceInfoPEntity> listallefence = new ArrayList<TInfoEfenceInfoPEntity>();

        TInfoEfenceInfoPShow tInfoEfenceInfoPShow = new TInfoEfenceInfoPShow();
        tInfoEfenceInfoPShow.setDevArea(devArea);
        List<TInfoEfenceInfoPShow> list = tInfoEfenceAreaService.getAllEfenceByDevArea(tInfoEfenceInfoPShow);

        for(int i=0;i<list.size();i++){
            if(list != null) {
                TInfoEfenceInfoPEntity tInfoEfenceInfoPEntity = new TInfoEfenceInfoPEntity();
                tInfoEfenceInfoPEntity.setDevArea(list.get(i).getDevArea());
                tInfoEfenceInfoPEntity.setDevCode(list.get(i).getDevCode());
                tInfoEfenceInfoPEntity.setDevName(list.get(i).getDevName());
                tInfoEfenceInfoPEntity.setDevAddr(list.get(i).getDevAddr());
                JSONArray array = new JSONArray();
                JSONObject obj = new JSONObject();
                obj.put("postCode", list.get(i).getPostCode());
                obj.put("postAddr", list.get(i).getPostAddr());
                obj.put("postX1", list.get(i).getPostX1());
                obj.put("postY1", list.get(i).getPostY1());
                obj.put("postX2", list.get(i).getPostX2());
                obj.put("postY2", list.get(i).getPostY2());
                obj.put("postNa", list.get(i).getPostNa());
                array.add(obj);
                list.remove(i);
                for (int j = 0; j < list.size(); j++) {
                    if(list != null) {
                        if (list.get(j).getDevCode().equals(tInfoEfenceInfoPEntity.getDevCode())) {
                            JSONObject objs = new JSONObject();
                            objs.put("postCode", list.get(j).getPostCode());
                            objs.put("postAddr", list.get(j).getPostAddr());
                            objs.put("postX1", list.get(j).getPostX1());
                            objs.put("postY1", list.get(j).getPostY1());
                            objs.put("postX2", list.get(j).getPostX2());
                            objs.put("postY2", list.get(j).getPostY2());
                            objs.put("postNa", list.get(j).getPostNa());
                            array.add(objs);
                            list.remove(j);
                        }
                    }
                }

                tInfoEfenceInfoPEntity.setDomains(array);

                listallefence.add(tInfoEfenceInfoPEntity);
            }
        }

        logger.debug("listallefence:" + listallefence);
//        list.add(tInfoEfenceAreaEntity);
        return R.ok().put("list", listallefence);
    }


    @RequestMapping("/upload")
//    @RequiresPermissions("substation:tinfoefencearea:upload")
    public R upload(@RequestParam("file") MultipartFile file,@RequestParam("devArea") long devArea) throws Exception {

        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        logger.debug("devArea:"+ devArea);
        logger.debug("文件长度:" + file.getSize());
        logger.debug("getOriginalFilename:" + file.getOriginalFilename());
        logger.debug("getName:" + file.getName());
        logger.debug("getContentType:" + file.getContentType());
        logger.debug("getResource:" + file.getResource());
//        String fileName = file.getName();
//        String path = file.getResource();
//        //这里我试了，可以用 fileName   也可以用  OriginalFilename   都没问题的
//        File f = new File(new File(path).getAbsolutePath()+ "/" + fileName);
//        file.transferTo(f);

        logger.debug("文件名:" + file.getOriginalFilename());
        String name = file.getOriginalFilename();
        int indx = file.getOriginalFilename().lastIndexOf(".");
        if(indx > 0) {
            name.substring(indx + 1);
        }
        logger.debug("name:"+name);
        logger.debug(" equals:"+name.equals("jpg") + " equals:" + name.equals("png"));
//        if(name.equals("jpg") || name.equals("png")) {

            byte[] data = null;
            InputStream is = file.getInputStream();
            data = new byte[is.available()];
            is.read(data);
            is.close();
            String encode = Base64.getEncoder().encodeToString(data);
            String pre = "";
            TInfoEfenceAreaEntity tInfoEfenceAreaEntity= new TInfoEfenceAreaEntity();
//            if (name.equals("jpg")){
//                pre = "data:image/jpeg;base64,"; // 加上前缀，用于html img标签显示成图片
//            }else{
//                pre = "data:image/png;base64,"; // 加上前缀，用于html img标签显示成图片
//            }
            tInfoEfenceAreaEntity.setDevArea(devArea);
//            tInfoEfenceAreaEntity.setDataType();
            tInfoEfenceAreaEntity.setAreaData(encode);
//            tInfoEfenceAreaEntity.setResVa1();
//            tInfoEfenceAreaEntity.setResVa2();
            tInfoEfenceAreaEntity.setCreateOpr((long)0);
            tInfoEfenceAreaEntity.setCreateTime(new Date());
            tInfoEfenceAreaEntity.setLastOpr((long)0);
            tInfoEfenceAreaEntity.setLastTime(new Date());


            int updsum = tInfoEfenceAreaService.updateValueByDevArea(tInfoEfenceAreaEntity);
            if(updsum <= 0) {
                logger.debug("新增围栏区域图片");
                boolean saveflag = tInfoEfenceAreaService.save(tInfoEfenceAreaEntity);
                if (!saveflag) {
                    throw new RRException("文件上传失败，文件信息保存失败");
                }
            }


            //上传文件
//        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String url = "图片上传成功";
            return R.ok().put("url", url);
//        }else{
//            throw new RRException("文件上传失败，文件名不符" + file.getOriginalFilename());
//        }
//        String url = "图片上传成功";
//        return R.ok().put("url", url);
    }

    /**
     * @Description  将常用需要校验的格式和区别其他格式的前几个字节写入map
     * @Param []
     * @return
     **/
    public void FileFormatVerify (){
        //if(fileFormat == null ){
        fileFormat = new HashMap<String, Object>();

        //JPEGvoid
        fileFormat.put("jpg","FFD8FFE0");
        //PNG
        fileFormat.put("png","89504E47");
//        fileFormat.put("zip","504B0304");
//        fileFormat.put("rar","52617221");
        //office类型，包括doc、xls和ppt
//           fileFormat.put("office","D0CF11E0");
        /**
         * docx ,xlsx和zip   相同  doc 和 xls 相同
         */
//        fileFormat.put("docx","504b0304");
//        fileFormat.put("doc","d0cf11e0");
//
//        fileFormat.put("xls","d0cf11e0");
//        fileFormat.put("xlsx","504b0304");
//        fileFormat.put("pdf","255044462");
        // }
    }

    /**
     * @Description 根据传入的文件获得后缀,获得指定文件格式byte[]数组中的前8位字符
     *              将传入文件转化为byte[]数组,取前8位.判断传入文件的前8位和我们指定好的文件byte[]的前8位是否相同,
     *              如果相同则文件格式没有被篡改,反之,文件后缀格式被篡改
     * @Param [file]
     * @return boolean 返回true 表示文件格式验证通过, 返回false 文件格式验证失败
     **/
    public boolean suffixVerify(MultipartFile file){
        String fileType = "";
        String name = file.getName();
        int i = name.lastIndexOf(".");
        // 获取文件的后缀
        if(i > 0){
            fileType = name.substring(i + 1);
        }
        //根据文件的后缀获取,获取文件的byte[]的前8位
//        if(fileFormat.containsKey(fileType.toLowerCase())){
//            String fileByte8 = String.valueOf(fileFormat.get(fileType.toLowerCase()));
//            //获取传入文件的byte[]的前8位
//            byte[] bytes = inputStream2ByteArray(file);
//            String compareByte = bytesToHexString(bytes);
//            //如果传入文件的byte[]的前8位和我们定义好的byte[]的前8位相同,验证通过.
//            if (compareByte.startsWith(fileByte8)){
//                //如果格式校验成功
//                return true;
//            }else{
//                return false;
//            }
//        }else{
//            return false;
//        }
        return false;
    }

}
